<template>
  <div>
    <!-- 风险经销商清单维护 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhRiskDealerListMaintain"
        :columns="columns"
        :isSelectColumn="false"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onRowSelectChange="selectChangeHandle"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="primary" @click="addHandle">新增</el-button>
          <el-button size="small" type="primary" @click="importHandler">导入</el-button>
          <multiuse-button size="small" type="primary" :click="exportHandler">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <Drawer :visible.sync="visible" :title="drawerTitle" :width="'80%'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SonModel :type="handleType" :rowData="formData" @close="emitCloseHandler" />
    </Drawer>
    <!-- 导入 -->
    <BaseDialog :visible.sync="visibleDialog" title="数据导入" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ImportFile :rowData="formData" @close="emitCloseHandler1" />
    </BaseDialog>
    <!-- 经销商查询 -->
    <BaseDialog :visible.sync="visibleDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OwnerSearch :rowData="formData" @close="emitCloseHandler2" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { queryList, importExcel, exportExcel,exporturl } from '@/api/omFinance/FinanceManage/RiskDealerListMaintain';
import { getRegion, getCommunity } from '@/api/omFinance/index';
import { exportExcelFile } from '@/utils/index';

import SonModel from './SonModel';
import ImportFile from './ImportFile';
import OwnerSearch from '../OwnerSearch';

export default {
  mixins: [dictionary],

  name: 'RiskDealerListMaintain',
  components: {
    SonModel,
    ImportFile,
    OwnerSearch
  },
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '详情' };
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      formData: {},
      visible: false,
      visibleDialog: false,
      visibleDealer: false,
      exportLoading: false,
      handleType: '',
      drawerTitle: '',
      deptDictList: []
    };
  },
  created() {},
  mounted() {
    this.getDeptData();
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    // 经销商查询
    searchHandle() {
      this.visibleDealer = true;
    },
    //加载事业部数据
    async getDeptData() {
      const res = await getRegion({});
      if (res.resultCode === 200) {
        res.data.map(x => {
          this.columns.find(item => item.dataIndex == 'deptId').filterItems.push({ text: x.orgName, value: x.id });
        });

        this.deptDictList = res.data.map(x => ({ codeId: x.id, codeCnDesc: x.orgName }));
        this.topFilterList.find(item => item.fieldName === 'deptId').itemList = res.data.map(x => ({ value: x.id, text: x.orgName }));
      }
    },
    //获取办事处下拉列表数据
    async getOfficeData(val) {
      const res = await getCommunity(val);
      if (res.resultCode === 200) {
        this.topFilterList.find(item => {
          if (item.fieldName === 'officeId') {
            item.initialValue = '';
            item.itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
          }
        });
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 新增
    addHandle() {
      this.handleType = 'add';
      this.formData = {};
      this.showHandler();
    },
    // 编辑
    editHandle(row) {
      this.handleType = 'edit';
      this.formData = row;
      this.showHandler();
    },
    showHandler() {
      this.drawerTitle = `${this.conf[this.handleType]}`;
      this.visible = true;
    },
    emitCloseHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    emitCloseHandler1(val, type) {
      this.visibleDialog = val;
    },
    emitCloseHandler2(val, data) {
      this.visibleDealer = val;
      if (data) {
        let dealerCodes = [];
        let dealerNames = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        this.topFilterList.find(x => x.fieldName == 'dealerCodes').initialValue = dealerCodes.toString();
      }
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    // 导入
    importHandler() {
      this.visibleDialog = true;
    },
    // 导出
    async exportHandler() {
      let json = Object.assign({}, { CODE: 'CODE_0000086' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;

      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, '风险经销商清单维护');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    // 选择当前行
    selectChangeHandle(row) {},
    async addHandle1(type) {
      if (type == 1) {
        await this.$confirm('是否通过?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {})
          .catch(() => {});
      } else {
        this.isreject = true;
      }
    },

    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '事业部',
          fieldName: 'deptId',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            if (val) {
              this.topFilterList.find(item => item.fieldName == 'officeId').initialValue = '';
              this.getOfficeData(val);
              return;
            }
            this.topFilterList.find(item => item.fieldName == 'officeId').initialValue = '';
            this.topFilterList.find(item => item.fieldName == 'officeId').itemList = [];
          }
        },
        {
          type: 'SELECT',
          label: '办事处',
          fieldName: 'officeId',
          placeholder: '请选择',
          initialValue: '',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '启用标记',
          fieldName: 'status',
          placeholder: '请选择',
          itemList: this.createDictList('1003')
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCodes',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.searchHandle()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row)}>
                  编辑
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '启用标记',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1003'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '1003')}</span>;
          }
        },
        {
          title: '事业部',
          dataIndex: 'deptId',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          render: props => {
            return <span>{this.transDictText(props.row.deptId, this.deptDictList)}</span>;
          }
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '移动比例',
          dataIndex: 'moveRatio',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '回款率',
          dataIndex: 'collectionRate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '库销系数',
          dataIndex: 'stockFactor',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '风险理由',
          dataIndex: 'riskReason',
          sorter: true,
          filter: true
        },
        {
          title: '管控措施',
          dataIndex: 'controlMeasure',
          sorter: true,
          filter: true
        },

        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '创建人',
          dataIndex: 'createdByName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '修改时间',
          dataIndex: 'updatedAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '修改人',
          dataIndex: 'updatedByName',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    }
  }
};
</script>
